<script setup lang="ts">
import type { ConsultIllness } from '@/types/consult'
import { ref } from 'vue'
import { showConfirmDialog, showToast, type UploaderFileListItem } from 'vant'
import type { UploaderAfterRead } from 'vant/lib/uploader/types'
import { uploadImage } from '@/services/consult'
import { computed } from 'vue'
import { useConsultStore } from '@/stores'
import { useRouter } from 'vue-router'
import { onMounted } from 'vue'
import { timeOptions, flagOptions } from '@/constants'

const form = ref<ConsultIllness>({
  // 病情描述
  illnessDesc: '',
  // 患病时间
  illnessTime: undefined,
  // 是否就诊
  consultFlag: undefined,
  // 图片描述
  pictures: []
})

// 选择到的图片信息，会自动的收集到 fileList
const fileList = ref<UploaderFileListItem[]>([])

// 选择成功会触发的回调
const onAfterRead: UploaderAfterRead = async (item) => {
  // !#1 只能是一个文件
  if (Array.isArray(item)) return showToast('只能选一张')
  // !#2 没有选择文件的情况
  if (!item.file) return showToast('请选择文件')
  // !#3 上传之前指定一下当前图片的状态
  item.status = 'uploading'
  item.message = '上传中...'
  try {
    // !#4 调用上传接口
    const r = await uploadImage(item.file)
    item.status = 'done'
    item.message = undefined
    item.url = r.data.url // 加这个的目的是为了后续能够根据 url 删除
    // 把后端返回的图片信息装到 form.value.pictures 里面
    form.value.pictures?.push(r.data)
  } catch (e) {
    item.status = 'failed'
    item.message = '上传失败'
  }
}
const onDeleteImg = (currentFile: UploaderFileListItem) => {
  // 循环 form.value.pictures，保留 item.url 不等于当前点击的这一项的 url
  form.value.pictures = form.value.pictures?.filter(
    (item) => item.url !== currentFile.url
  )
}
const disabled = computed(() => {
  return (
    form.value.illnessDesc === '' ||
    form.value.illnessTime === undefined ||
    form.value.consultFlag === undefined
  )
})

// 把 form 信息记录到 Pinia

const consultStore = useConsultStore()
const router = useRouter()

const next = () => {
  if (!form.value.illnessDesc) return showToast('请输入病情描述')
  if (form.value.illnessTime === undefined)
    return showToast('请选择症状持续时间')
  if (form.value.consultFlag === undefined)
    return showToast('请选择是否已经就诊')
  consultStore.setIllness(form.value)
  // 跳转档案管理，需要根据 isChange 来区分，是否可以选择卡片
  router.push('/user/patient?isChange=1')
}

onMounted(async () => {
  // 有没有描述信息
  if (consultStore.consult.illnessDesc) {
    await showConfirmDialog({
      title: '温馨提示',
      message: '是否恢复您之前填写的病情信息呢？',
      // 配置确认按钮的颜色
      confirmButtonColor: 'var(--cp-primary)',
      // 页面回退的时候也展示弹框
      closeOnPopstate: false
    })
    // 把 store 里面的信息取出来重新赋值给 form.value
    const { illnessDesc, illnessTime, consultFlag, pictures } =
      consultStore.consult
    form.value = { illnessDesc, illnessTime, consultFlag, pictures }
    // 单独处理图片回填，pictures => [{ id, url }]
    fileList.value = pictures || []
  }
})
</script>

<template>
  <div class="consult-illness-page">
    <cp-nav-bar title="图文问诊" />
    <div class="illness-tip van-hairline--bottom">
      <img class="img" src="@/assets/avatar-doctor.svg" />
      <div class="info">
        <p class="tit">在线医生</p>
        <p class="tip">
          请描述你的疾病或症状、是否用药、就诊经历，需要我听过什么样的帮助
        </p>
        <p class="safe">
          <cp-icon name="consult-safe" /><span>内容仅医生可见</span>
        </p>
      </div>
    </div>
    <!-- 表单 -->
    <div class="illness-form">
      <van-field
        type="textarea"
        rows="3"
        placeholder="请详细描述您的病情，病情描述不能为空"
        v-model="form.illnessDesc"
      ></van-field>
      <div class="item">
        <p>本次患病多久了？</p>
        <cp-radio-btn :options="timeOptions" v-model="form.illnessTime" />
      </div>
      <div class="item">
        <p>此次病情是否去医院就诊过？</p>
        <cp-radio-btn :options="flagOptions" v-model="form.consultFlag" />
      </div>
      <!-- 图片上传 -->
      <div class="illness-img">
        <van-uploader
          v-model="fileList"
          :after-read="onAfterRead"
          @delete="onDeleteImg"
          max-count="9"
          :max-size="5 * 1024 * 1024"
          upload-icon="photo-o"
          upload-text="上传图片"
        ></van-uploader>
        <p class="tip" v-if="fileList.length === 0">
          上传内容仅医生可见,最多9张图,最大5MB
        </p>
      </div>
      <van-button :class="{ disabled }" @click="next" type="primary" block round
        >下一步</van-button
      >
    </div>
  </div>
</template>

<style lang="scss" scoped>
.consult-illness-page {
  padding-top: 46px;
  .illness-tip {
    display: flex;
    padding: 15px;
    .img {
      width: 52px;
      height: 52px;
      border-radius: 4px;
      overflow: hidden;
      margin-top: 10px;
    }
    .info {
      flex: 1;
      padding-left: 12px;
      .tit {
        font-size: 16px;
        margin-bottom: 5px;
      }
      .tip {
        padding: 12px;
        background: var(--cp-bg);
        color: var(--cp-text3);
        font-size: 13px;
        margin-bottom: 10px;
      }
      .safe {
        font-size: 10px;
        color: var(--cp-text3);
        display: flex;
        align-items: center;
        .cp-icon {
          font-size: 12px;
          margin-right: 2px;
        }
      }
    }
  }
  .illness-form {
    padding: 15px;
    .van-field {
      padding: 0;
      &::after {
        border-bottom: none;
      }
    }
    .item {
      > p {
        color: var(--cp-text3);
        padding: 15px 0;
      }
    }
  }
  .van-button {
    font-size: 16px;
    margin-bottom: 30px;
    &.disabled {
      opacity: 1;
      background: #fafafa;
      color: #d9dbde;
      border: #fafafa;
    }
  }
}

.illness-img {
  padding-top: 16px;
  margin-bottom: 40px;
  display: flex;
  align-items: center;
  .tip {
    font-size: 12px;
    color: var(--cp-tip);
  }
  ::v-deep() {
    .van-uploader__wrapper {
      justify-content: space-between;
    }
    .van-uploader {
      &__preview {
        &-delete {
          left: -6px;
          top: -6px;
          border-radius: 50%;
          background-color: var(--cp-primary);
          width: 20px;
          height: 20px;
          &-icon {
            transform: scale(0.9) translate(-22%, 22%);
          }
        }
        &-image {
          border-radius: 8px;
          overflow: hidden;
        }
      }
      &__upload {
        border-radius: 8px;
      }
      &__upload-icon {
        color: var(--cp-text3);
      }
    }
  }
}
</style>
